package sourceapi.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.*;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootPanel;

public class MenuManager implements RequestCallback {
	
	public static ArrayList<MenuItem> MenuList = new ArrayList<MenuItem>();
	
	public void onError(Request request, Throwable exception) {
		// Couldn't connect to server (could be timeout, SOP violation, etc.)     
	}

	public void onResponseReceived(Request request, Response response) {
		
		if (200 == response.getStatusCode()) {
			
			JSONObject ValueArray = JSONParser.parse( response.getText() ).isObject();
			
			if( ValueArray == null ){
				GWT.log("Failed to parse main request", null );
				return;
			}
			
			Set<String> NameList = ValueArray.keySet();
			Iterator<String> FileKeys = NameList.iterator();
			
			while( FileKeys.hasNext() ){
				
				String name = FileKeys.next();
				int id = Integer.parseInt( name );
				
				MenuItem Item = new MenuItem( id, ValueArray.get( name ).isObject() );
					
				
				MenuList.add( Item );
				
			}
			
		} else {
		}
		
		Collections.sort( MenuList );
		
		for( MenuItem Item : MenuList )
			RootPanel.get("MenuSpace").add( Item );		
		
	    // Now that we've setup our listener, fire the initial history state.
	    History.fireCurrentHistoryState();
	      
	}   
	
	public static void UpdateMenus(){
		
		GWT.log("Searching for: " + SourceAPI.MainSearchBox.getText(), null );
		
		boolean OnSearch = SourceAPI.ShouldSearch();
		
		//If we are searching, we have certain limitations
		for( MenuItem Item : MenuList ){
			
			if( OnSearch )
				Item.OpenSearchMenu();
			else
				Item.CloseMenu();
			
		}
	}
	
	public static void CloseAllMenus(){
		
		for( MenuItem Item : MenuList )
			Item.CloseMenu();
		
	}
	
	public static MenuItem Get( String Name ){
		
		for( MenuItem Item : MenuList ){

			if( Name.equalsIgnoreCase( Item.Name ) )
				return Item;
		}
		
		return null;
		
	}
	
}
